package org.apache.solr.ocean.http;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.logging.Logger;

import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpMethodBase;
import org.apache.commons.httpclient.util.EncodingUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.solr.common.util.NamedList;
import org.apache.solr.ocean.util.XMLUtil;
import org.jdom.Element;

/**
 * 
 * @author jasonr
 */
public class HttpResponse {
	public static Logger log = Logger.getLogger(HttpResponse.class.getName());
	public URL url;
	public HttpMethod httpMethod;
	public byte[] bytes;
	public String responseCharSet;
	public int statusCode;
	public Object attachment;
	public NamedList<String> headers;

	public HttpResponse() {
	}

	public HttpResponse(HttpMethod httpMethod) throws IOException {
		this.httpMethod = httpMethod;
		responseCharSet = ((HttpMethodBase) httpMethod).getResponseCharSet();
		statusCode = httpMethod.getStatusCode();
		bytes = httpMethod.getResponseBody();
	}

	public OceanXML getOceanXML() throws Exception {
		Element element = XMLUtil.parseElement(getBodyString());
		return new OceanXML(element);
	}

	public String toString() {
		return "statusCode: " + statusCode + " attachment: " + attachment + " " + getBodyString();
	}

	public InputStream getBodyStream() throws IOException {
		return new ByteArrayInputStream(bytes);
	}

	public byte[] getBytes() {
		return bytes;
	}

	public String getBodyString() {
		if (StringUtils.isBlank(responseCharSet)) {
			responseCharSet = "ISO-8859-1";
		}
		return EncodingUtil.getString(bytes, responseCharSet);
	}
}
